package com.itheima.service.impl;

import com.itheima.mapper.BrandMapper;
import com.itheima.pojo.Brand;
import com.itheima.pojo.PageBean;
import com.itheima.service.BrandService;
import com.itheima.util.SqlSessionFactoryUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import java.util.List;

/**
 *使用接口，可以解开service和servlet的耦合
 */

public class BrandServiceImpl implements BrandService {

    SqlSessionFactory sqlSessionFactory=SqlSessionFactoryUtils.getSqlSessionFactory();

    /**
     * 查询所有
     * @return
     */
    @Override
    public List<Brand> selectAll() {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        List<Brand> brands = mapper.selectAll();

        sqlSession.close();

        return brands;

    }

    /**
     * 插入数据
     * @param brand
     * @return
     */
    @Override
    public void insert(Brand brand) {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        mapper.insert(brand);
        sqlSession.commit();
        sqlSession.close();
    }

    /**
     * 批量删除
     * @param ids
     */
    @Override
    public void deleteByIds(int[] ids) {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        mapper.deleteByIds(ids);
        sqlSession.commit();
        sqlSession.close();
    }

    @Override
    public PageBean<Brand> selectByPages(int currentPage, int pageSize) {
        //1.获取mapper对象
        SqlSession sqlSession = sqlSessionFactory.openSession();
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        //2.计算当前页开始的索引：（当前页数-1）*每页展示条数
        int index=(currentPage-1)*pageSize;

        //3.获取每页展示的数量
        int size=pageSize;

        //4.调用数据访问层的selectAllCount方法,获取当前所有数据
        int count = mapper.selectAllCount();

        //5.调用数据访问层的selectByPage方法，获取当前页的数据
        List<Brand> brands = mapper.selectByPage(index, size);

        //6.将count和brands封装成pageBean对象
        PageBean<Brand> pageBean=new PageBean<>();
        pageBean.setTotalCount(count);
        pageBean.setCurrentRows(brands);

        //关闭资源
        sqlSession.close();
        //返回Page对象
        return pageBean;

    }


}
